package com.gkt.ec.cms.activity.controller;

import com.github.pagehelper.PageInfo;
import com.gkt.ec.cms.activity.model.domain.CompanyEntity;
import com.gkt.ec.cms.activity.model.domain.CustomerActivityEntity;
import com.gkt.ec.cms.activity.model.domain.CustomerVehicle;
import com.gkt.ec.cms.activity.model.domain.CustomerVehicleEntity;
import com.gkt.ec.cms.activity.model.domain.MarketActivityEntity;
import com.gkt.ec.cms.activity.model.pojo.SearchCustomerVO;
import com.gkt.ec.cms.activity.service.ActivityService;
import com.gkt.ec.cms.activity.service.CustomerVehicleService;
import com.gkt.ec.cms.commons.enhance.AnonymousAccess;
import com.gkt.ec.cms.commons.enhance.Login;
import com.gkt.ec.cms.commons.model.domain.AdminUser;
import com.gkt.ec.commons.persistence.constants.customer.CustomerUserAgeRange;
import com.gkt.ec.commons.persistence.constants.customer.VehicleDistance;
import com.gkt.ec.commons.persistence.constants.customer.VehicleYears;
import com.gkt.ec.commons.persistence.entity.search.CouponSearch;
import com.gkt.ec.commons.shared.persistence.PageQuery;
import com.gkt.library.commons.shared.utils.StringUtils;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 14081593 on 2015/11/28.
 * 查询用户信息类
 */
@Controller
@AnonymousAccess
@RequestMapping(value = "/customerVehicle")
public class CustomerVehicleController {
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private CustomerVehicleService customerVehicleService;
    @Autowired
    private ActivityService activityService;
    //车辆品牌型号集合
    private List<HashMap> vehicleBrandList = new ArrayList<HashMap>();

    /**
     * 查找活动对象
     * @param model
     * @return
     */
    @RequestMapping(value = "/queryCustomerVehicleList")
    public String queryCustomerVehicleList(Map<String, Object> model, Long activityId,Integer activityTargetType, String selectCustomers){
        model.put("ageEnum", CustomerUserAgeRange.values());
        model.put("millsEnum", VehicleDistance.values());
        model.put("vehicleYearsEnum", VehicleYears.values());
        model.put("activityTargetType", activityTargetType);
        model.put("activityId", activityId);
        model.put("selectCustomers", selectCustomers);
        //获取选择的用户列表
//        List<CustomerActivityEntity> customerList = activityService.queryAllCustomerActivity(activityId);
//        List<String> customerIdList = new ArrayList<String>();
//        for(CustomerActivityEntity ce : customerList) {
//            customerIdList.add(ce.getCustomId());
//        }
//        if(CollectionUtils.isNotEmpty(customerIdList)) {
//            model.put("selectCustomers", StringUtils.join(customerIdList.toArray(), ","));
//        }
        log.info("selectCustomers  model============" +model );
        return "/activityManager/customerVehicleList";
    }

    /**
     * 搜索活动对象
     * @param searchCondition
     * @param request
     * @return
     */
    @RequestMapping(value = "/search")
    @ResponseBody
    public Object search(SearchCustomerVO searchCondition,HttpServletRequest request){
        int offset = NumberUtils.toInt(request.getParameter("offset"), 0);
        int max = NumberUtils.toInt(request.getParameter("limit"), 15);

        //获取该活动已经绑定的用户列表
//        if(searchCondition.getActivityId() != null) {
//            List<Map<String,String>> bindCustomerList = customerVehicleService.queryBindCustomers(searchCondition.getActivityId());
//
//            List<String> bindCustomers = new ArrayList<String>();
//            for(Map<String,String> customerMap : bindCustomerList) {
//                bindCustomers.add(customerMap.get("custom_id"));
//            }
//            searchCondition.setBindCustomers(bindCustomers);
//        }
        log.info("customerVehicleService searchCondition:" + searchCondition);
        PageInfo<CustomerVehicleEntity> pageInfo = customerVehicleService.queryAll(searchCondition,offset,max);
        return pageInfo;
    }

    /**
     * 查询活动品牌
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping(value = "/queryVehicleBrand")
    public String queryVehicleBrand(HttpServletRequest request,Long activityId, HttpServletResponse response,Map<String, Object> model) {
        MarketActivityEntity me = activityService.getActivityDetail(activityId);

        model.put("curVehicle",me.getSearchVehicle());
        model.put("activityId",activityId);
        return "/activityManager/vehicleBrandList";
    }
    
    /**
     * 查询活动品牌
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping(value = "/queryVehicleBrandCoupon")
    public String queryVehicleBrandCoupon(HttpServletRequest request, HttpServletResponse response,Map<String, Object> model) {

        return "/coupon/vehicleBrandList";
    }
    
    /**
     * 搜索活动品牌-优惠功能按照用户选择
     * @param model
     * @param user
     * @return
     */
    @RequestMapping(value = "/queryVehicleCouponJson")
    @ResponseBody
    public String queryVehicleCouponJson(Map<String, Object> model,@Login AdminUser user){

        if(CollectionUtils.isEmpty(vehicleBrandList)) {
            vehicleBrandList = customerVehicleService.queryVehicleBrand();
        }

        HashMap<String,String> brandMap = new HashMap();
        List<String> brandList = new ArrayList<String>();
        for(HashMap vehicle : vehicleBrandList) {
            String id = vehicle.get("id") + "";
            String seriesId = vehicle.get("seriesId") + "";
            String brandName = vehicle.get("brandName") + "";
            String seriesName = vehicle.get("seriesName") + "";
            String py = vehicle.get("py") + "";

            StringBuffer sb = new StringBuffer();
            String tmpName = brandMap.get(id);
            //默认选中样式
            StringBuffer checkedBuffer = new StringBuffer();
            checkedBuffer.append("\"state\"").append(":").append("{").append("\"selected\"").append(":true}");
            if(StringUtils.isEmpty(tmpName)) {
                brandMap.put(id, brandName);
                sb.append("{").append("\"id\"").append(":").append("\"").append(id).append("\"")
                        .append(",").append("\"parent\"").append(":").append("\"").append("#").append("\"")
                        .append(",").append("\"text\"").append(":").append("\"").append(brandName).append("\"").append("}");
                brandList.add(sb.toString());

                sb.setLength(0);
                sb.append("{").append("\"id\"").append(":").append("\"").append(seriesId).append("\"")
                        .append(",").append("\"parent\"").append(":").append("\"").append(id).append("\"")
                        .append(",") .append("\"text\"").append(":").append("\"") .append(seriesName).append("\"");
               
                sb.append("}");

                brandList.add(sb.toString());
                continue;
            }
            sb.append("{").append("\"id\"").append(":").append("\"").append(seriesId).append("\"")
                    .append(",").append("\"parent\"").append(":").append("\"").append(id).append("\"")
                    .append(",") .append("\"text\"") .append(":").append("\"") .append(seriesName).append("\"");
           
            sb.append("}");

            brandList.add(sb.toString());
        }
        //log.info("==============" + brandList.toString());

        return brandList.toString();
    }

    /**
     * 搜索活动品牌
     * @param model
     * @param user
     * @return
     */
    @RequestMapping(value = "/queryVehicleJson")
    @ResponseBody
    public String queryVehicleJson(Map<String, Object> model,Long activityId,@Login AdminUser user){

        MarketActivityEntity activityDetail = activityService.getActivityDetail(activityId) ;
        String selectedVehicleIds = activityDetail.getSearchVehicleIds();
        log.info("selectedVehicleIds========" + selectedVehicleIds);

        if(CollectionUtils.isEmpty(vehicleBrandList)) {
            vehicleBrandList = customerVehicleService.queryVehicleBrand();
        }

        HashMap<String,String> brandMap = new HashMap();
        List<String> brandList = new ArrayList<String>();
        for(HashMap vehicle : vehicleBrandList) {
            String id = vehicle.get("id") + "";
            String seriesId = vehicle.get("seriesId") + "";
            String brandName = vehicle.get("brandName") + "";
            String seriesName = vehicle.get("seriesName") + "";
            String py = vehicle.get("py") + "";

            StringBuffer sb = new StringBuffer();
            String tmpName = brandMap.get(id);
            //默认选中样式
            StringBuffer checkedBuffer = new StringBuffer();
            checkedBuffer.append("\"state\"").append(":").append("{").append("\"selected\"").append(":true}");
            if(StringUtils.isEmpty(tmpName)) {
                brandMap.put(id, brandName);
                sb.append("{").append("\"id\"").append(":").append("\"").append(id).append("\"")
                        .append(",").append("\"parent\"").append(":").append("\"").append("#").append("\"")
                        .append(",").append("\"text\"").append(":").append("\"").append(brandName).append("\"").append("}");
                brandList.add(sb.toString());

                sb.setLength(0);
                sb.append("{").append("\"id\"").append(":").append("\"").append(seriesId).append("\"")
                        .append(",").append("\"parent\"").append(":").append("\"").append(id).append("\"")
                        .append(",") .append("\"text\"").append(":").append("\"") .append(seriesName).append("\"");
                if(StringUtils.isNotEmpty(selectedVehicleIds) && selectedVehicleIds.indexOf(seriesId) >=0 ) {
                    sb.append(",").append(checkedBuffer);
                }
                sb.append("}");

                brandList.add(sb.toString());
                continue;
            }
            sb.append("{").append("\"id\"").append(":").append("\"").append(seriesId).append("\"")
                    .append(",").append("\"parent\"").append(":").append("\"").append(id).append("\"")
                    .append(",") .append("\"text\"") .append(":").append("\"") .append(seriesName).append("\"");
            if(StringUtils.isNotEmpty(selectedVehicleIds) && selectedVehicleIds.indexOf(seriesId) >=0 ) {
                sb.append(",").append(checkedBuffer);
            }
            sb.append("}");

            brandList.add(sb.toString());
        }
        //log.info("==============" + brandList.toString());

        return brandList.toString();
    }

    /**
     * 参与活动的用户列表
     * @param model
     * @return
     */
    @RequestMapping(value = "/getActivityCustomer")
    public String getActivityCustomer(Map<String, Object> model,@RequestParam Long id,String isShowButton,Integer activityTargetType){
        model.put("ageEnum", CustomerUserAgeRange.values());
        model.put("millsEnum", VehicleDistance.values());
        model.put("vehicleYearsEnum", VehicleYears.values());
        model.put("activityId", id);
        model.put("activityTargetType", activityTargetType);
        if(StringUtils.isNotEmpty(isShowButton)) {
            model.put("isShowButton", "1".equals(isShowButton) ? "1":"0");
        }
        log.info("model============" + model);
        return "/activityManager/activityCustomerList";
    }

    /**
     * 搜索用户列表
     * @param searchCondition
     * @param request
     * @return
     */
    @RequestMapping(value = "/queryActivityCustomer")
    @ResponseBody
    public Object queryActivityCustomer(SearchCustomerVO searchCondition,HttpServletRequest request){
        int offset = NumberUtils.toInt(request.getParameter("offset"), 0);
        int max = NumberUtils.toInt(request.getParameter("limit"), 15);

        PageInfo<CustomerActivityEntity> pageInfo = customerVehicleService.queryActivityCustomer(searchCondition,offset,max);
        return pageInfo;
    }
    
    /**
     *用户信息查询列表-分页查询 
     * @param offset
     * @param limit
     * @param searchCondition
     * @return
     */
    
    @RequestMapping(value = "/queryByPage")
    @ResponseBody
    public Object queryByPage(String offset,String limit, SearchCustomerVO searchCondition){
    	
    	int off = NumberUtils.toInt(offset, 0);
        int max = NumberUtils.toInt(limit, 15);
    	
        log.info(String.format("queryByPage [%s]", searchCondition));
        PageInfo<CustomerVehicle> page = customerVehicleService.queryByPage(searchCondition, off, max);
        return page;
    }
    
    @RequestMapping(value = "/queryBindByPage")
    @ResponseBody
    public Object queryBindByPage(String offset,String limit, CouponSearch searchCondition){
    	
    	int off = NumberUtils.toInt(offset, 0);
        int max = NumberUtils.toInt(limit, 15);
    	
        log.info(String.format("queryByPage [%s]", searchCondition));
        PageInfo<CustomerVehicle> page = customerVehicleService.queryBindByPage(searchCondition, off, max);
        return page;
    }
    
    @RequestMapping(value = "/userSelect")
    public String userSelect(Map<String, Object> model){
        log.info(String.format("userSelect [ %s ]", model));
        
        CustomerUserAgeRange[] ageRanges = CustomerUserAgeRange.values();
        VehicleDistance[] distance = VehicleDistance.values();
        VehicleYears[] years = VehicleYears.values();
        
        model.put("ageRanges", ageRanges);
        model.put("distance", distance);
        model.put("years", years);
        return "/coupon/userselect";
    }
}
